package com.mrd.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;


public class SerializeUtil implements RedisSerializer<Object> {

  static final byte[] EMPTY_ARRAY = new byte[0];
  private final Charset charset;

  public SerializeUtil() {
    // TODO Auto-generated constructor stub
    this(Charset.forName("UTF8"));
  }

  public SerializeUtil(Charset charset) {
    // TODO Auto-generated constructor stub
    Assert.notNull(charset);
    this.charset = charset;
  }

  @Override
  public byte[] serialize(Object object) { // 序列化方法
    if (object == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      ObjectOutputStream outo = new ObjectOutputStream(out);
      outo.writeObject(object);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return out.toByteArray();
  }

  @Override
  public Object deserialize(byte[] b) throws SerializationException { // 反序列化
    if (b == null) {
      return null;
    }
    ObjectInputStream oin;
    try {
      oin = new ObjectInputStream(new ByteArrayInputStream(b));
      try {
        return oin.readObject();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }

}
